package edu.goku.examples.httpsdemo.client;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.*;
import java.security.cert.CertificateException;
import java.time.Duration;

/**
 * @author fuyongde
 * @date 2020/12/6 20:44
 */
public class Java11HttpsUtils {

    public static void main(String[] args) throws IOException, InterruptedException, KeyStoreException,
            CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
        // 如需禁用 HostnameVerification
        // System.setProperty("jdk.internal.httpclient.disableHostnameVerification", "true");

        InputStream inputStream = HttpsUtils.class.getResourceAsStream("/certs/client.p12");
        //创建KeyStore，用来存储信任证书
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(inputStream, "111111".toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "111111".toCharArray());

        String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
        tmf.init(keyStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());

        HttpClient httpClient = HttpClient.newBuilder()
                .sslContext(sslContext)
                .build();

        // 创建一个自定义的HTTP请求对象
        HttpRequest request = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create("https://www.goku.edu:8443/index/hello"))
                .header("Accept-Language", "zh-CN")
                .timeout(Duration.ofMillis(5000))
                .build();
        // 客户端传递请求信息，且返回字符串形式的应答报文
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}
